package com.sino.operation.service.business;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sino.operation.commons.ConstantValue;
import com.sino.operation.commons.commonEnum.StatusInfoEnum;
import com.sino.operation.dto.Dto;
import com.sino.operation.entity.*;
import com.sino.operation.param.inner.TaskBackParam;
import com.sino.operation.param.inner.TaskBackPublicParam;
import com.sino.operation.param.inner.TaskCompleteParam;
import com.sino.operation.param.inner.TaskCompletePublicParam;
import com.sino.operation.param.out.EscReciveByCounter;
import com.sino.operation.peripheral.esc.request.EscBody;
import com.sino.operation.peripheral.esc.request.NetHandle;
import com.sino.operation.util.PersistenceUtil;
import com.sino.operation.util.StringUtil;
import com.sino.operation.util.TimeUtil;
import com.sino.operation.vo.ExchangeVo;
import com.sino.operation.vo.PublicInfo;
import com.sino.operation.vo.current.TaskOtherCompleteParam;
import lombok.extern.log4j.Log4j2;
import org.junit.Test;

import java.util.*;

@Log4j2
public class Exec_710302 extends BaseAction {



    public Exec_710302(Map varMap, BizTranslist bizTranslist, SysAbMessage sysAbMessage, BizOperateLog bizOperateLog, Object registerTable, Object receiveParam) {
        super(varMap, bizTranslist, sysAbMessage, bizOperateLog, registerTable, receiveParam);
    }

    public Exec_710302(String journalNo, SysAbMessage sysAbMessage) {
        super(journalNo, sysAbMessage);
    }

    //发起流程业务处理
    @Override
    public PersistenceUtil executeReception() throws Exception {
        EscReciveByCounter receiveParam = (EscReciveByCounter) this.receiveParam;
        EscBody escBody = receiveParam.getEscBody();
        PublicInfo publicInfo = escBody.getPublicInfo();
        String json = JSONObject.toJSONString(receiveParam.getEscBody().getObject());
        ExchangeVo exchangeVo = JSONObject.parseObject(json, ExchangeVo.class);
        String account_type = exchangeVo.getACCOUNT_TYPE();//账户类型
        String postchar = exchangeVo.getPOSTCHAR();//邮电费
        String voucher_type = exchangeVo.getVOUCHER_TYPE();//凭证类型
        String agent_name = exchangeVo.getAGENT_NAME();//代理人名字
        String agent_prox_num = exchangeVo.getAGENT_PROX_NUM();// 代理人证件号
        String agent_prox_type = exchangeVo.getAGENT_PROX_TYPE();//代理人证件类型
        String bill_date = exchangeVo.getBILL_DATE();//票据日期
        String bill_num = exchangeVo.getBILL_NUM();//票据号码
        String expath_code = exchangeVo.getEXPATH_CODE();//汇路代码
        String handling_fee = exchangeVo.getHANDLING_FEE();//手续费
        String toll_type = exchangeVo.getTOLL_TYPE();//收费方式
        String prox_type = exchangeVo.getPROX_TYPE();//证件类型
        String prox_num = exchangeVo.getPROX_NUM();//证件号码
        String tran_pass = exchangeVo.getTRAN_PASS();//交易密码
        String expathOpt = exchangeVo.getExpathOpt();//汇路选择
        String certyTrust = exchangeVo.getCertyTrust();//凭证种类（委托收款附加域）
        String currency = exchangeVo.getCurrency();//币种
        String wdmd = exchangeVo.getWdmd();//支取方式
        log.info("流程发起报文:" + exchangeVo.toString());
        String imageId = publicInfo.getImageId();//影像套号
        String tranCode = publicInfo.getTranCode();//交易码
        String businessType = publicInfo.getBusinessType();//业务类型
        String journalNo = this.bizTranslist.getJournalNo();
        BizExchangeInfo bizExchangeInfo = new BizExchangeInfo();

        // 判断走整单还是走切片(1表示走切片，2表示走整单).从报文中取出证明文件种类，若为77、78、80、81、99，则走整单，其他情况都走切片
        String[] ts = {"", "01", "18", "23", "38", "71", "72", "73", "77", "78", "80", "81", "99"};
        List<String> types = Arrays.asList(ts);
        // 验证证明文件种类是否正确
        if (voucher_type == null || !types.contains(voucher_type)) {
            return null;
        }

        String cps_flag = null;
        // 确定切片标志 放入流程变量 加入报文 更新登记簿表
        if (!"".equals(voucher_type) && Integer.valueOf(voucher_type.trim()) < 77) {
            cps_flag = "1";
        } else {
            cps_flag = "2";
        }
        exchangeVo.setJournalNo(journalNo);
        escBody.setObject(exchangeVo);
        receiveParam.setEscBody(escBody);
        bizExchangeInfo.setJournalNo(journalNo);
        bizExchangeInfo.setBsty(voucher_type);
        bizExchangeInfo.setPoschar(postchar);
        bizExchangeInfo.setCpsFlag(cps_flag);
        bizExchangeInfo.setAccty(account_type);
        bizExchangeInfo.setImageId(imageId);
        bizExchangeInfo.setProxDno(agent_prox_num);
        bizExchangeInfo.setProxName(agent_name);
        bizExchangeInfo.setProxDty(agent_prox_type);
        bizExchangeInfo.setExpath(expath_code);
        bizExchangeInfo.setTransCode(tranCode);
        bizExchangeInfo.setBsty(businessType);
        bizExchangeInfo.setPoundage(handling_fee);
        bizExchangeInfo.setCerdateTrust(bill_date);
        bizExchangeInfo.setCernoTrust(bill_num);
        bizExchangeInfo.setCertyTrust(certyTrust);
        bizExchangeInfo.setTolltype(toll_type);
        bizExchangeInfo.setWdmd(wdmd);
        bizExchangeInfo.setDocty(prox_type);
        bizExchangeInfo.setDocno(prox_num);
        bizExchangeInfo.setTranspwd(tran_pass);
        bizExchangeInfo.setCurrency(currency);
        bizExchangeInfo.setExpathOpt(expathOpt);
        this.bizTranslist.setSliceFlage(cps_flag);
        varMap.put("cps_flag", cps_flag);
        persistence.addEntity(bizExchangeInfo);
        return persistence;
    }

    //整单1提交方法
    public PersistenceUtil executeTotalEntry1() throws Exception {
        TaskOtherCompleteParam receiveParam = (TaskOtherCompleteParam) this.receiveParam;
        String json = JSON.toJSONString(receiveParam);
        this.sysAbMessage.setMessageTotal1(json);
        return persistence;
    }

    public PersistenceUtil executeTotalEntry2() throws Exception {
        TaskOtherCompleteParam receiveParam = (TaskOtherCompleteParam) this.receiveParam;
        String json = JSON.toJSONString(receiveParam);
        this.sysAbMessage.setMessageTotal2(json);
        return persistence;
    }

    //修正岗提交方法
    public PersistenceUtil executeFixed() throws Exception {
        TaskOtherCompleteParam receiveParam = (TaskOtherCompleteParam) this.receiveParam;
        String json = JSON.toJSONString(receiveParam);
        String sliceFlage = bizTranslist.getSliceFlage();
        String journalNo = bizTranslist.getJournalNo();
        BizExchangeInfo bizExchangeInfo = bizExchangeInfoMapper.selectById(journalNo);
        Map<String, Map> infoInputs = receiveParam.getInfoInputs();
        bizExchangeInfo= Exec_710302_Util.CollectionHandle(infoInputs, bizExchangeInfo);//归集登记薄数据
        if (StatusInfoEnum.SLICE_FLAGE.getCode().equals(sliceFlage)) {
            this.varMap.put("cps_flag", StatusInfoEnum.SLICE_FLAGE.getCode());
        } else {
            this.varMap.put("cps_flag", StatusInfoEnum.TOTAL_FLAGE.getCode());
        }
        this.sysAbMessage.setMessageAuditing(json);
        this.sysAbMessage.setMessage(json);//
        persistence.addEntity(bizExchangeInfo);
        return persistence;
    }

    //验印岗1提交方法
    public PersistenceUtil executeVerify1() {
        TaskOtherCompleteParam receiveParam = (TaskOtherCompleteParam) this.receiveParam;
        TaskCompletePublicParam taskCompletePublicParam = receiveParam.getTaskCompletePublicParam();
        String completeMark = taskCompletePublicParam.getCompleteMark();
        if (completeMark.equals("4")) {
            String verifyReason = taskCompletePublicParam.getVerifyReason();
            String verifyReasonType = taskCompletePublicParam.getVerifyReasonType();
            this.bizOperateLog.setOperateType(verifyReasonType);
            this.bizOperateLog.setOperReason(verifyReason);
        }
        return persistence;
    }

    //验印岗2提交方法
    public PersistenceUtil executeVerify2() {
        TaskOtherCompleteParam receiveParam = (TaskOtherCompleteParam) this.receiveParam;
        TaskCompletePublicParam taskCompletePublicParam = receiveParam.getTaskCompletePublicParam();
        String completeMark = taskCompletePublicParam.getCompleteMark();
        if (completeMark.equals("4")) {
            String verifyReason = taskCompletePublicParam.getVerifyReason();
            String verifyReasonType = taskCompletePublicParam.getVerifyReasonType();
            this.bizOperateLog.setOperateType(verifyReasonType);
            this.bizOperateLog.setOperReason(verifyReason);
        }
        return persistence;
    }

    //复核岗提交方法
    public PersistenceUtil executeReview() {
        TaskOtherCompleteParam receiveParam = (TaskOtherCompleteParam) this.receiveParam;
        Map<String, Map> infoInputs = receiveParam.getInfoInputs();
        String journalNo = bizTranslist.getJournalNo();
        BizExchangeInfo bizExchangeInfo = bizExchangeInfoMapper.selectById(journalNo);
        String payAcc = infoInputs.get("PAY_ACC").get("value").toString();//付款人账号
        String payName = infoInputs.get("PAY_NAME").get("value").toString();//付款人姓名
        String payAddr = infoInputs.get("PAY_ADDR").get("value").toString();//付款人地址
        String amount = infoInputs.get("AMOUNT").get("value").toString();//金额
        String cerno = infoInputs.get("CERNO").get("value").toString();//凭证号码
        String cerdate = infoInputs.get("CERDATE").get("value").toString();//凭证日期
        String paypwd = infoInputs.get("PAYPWD").get("value").toString();//支付密码
        String recvAcc = infoInputs.get("RECV_ACC").get("value").toString();//收款人账号
        String recvName = infoInputs.get("RECV_NAME").get("value").toString();//收款人姓名
        String recvAddr = infoInputs.get("RECV_ADDR").get("value").toString();//收款人地址
        String businessKind = infoInputs.get("BUSINESS_KIND").get("value").toString();//业务类型
        String remarks = infoInputs.get("REMARKS").get("value").toString();//备注
        String grade = infoInputs.get("GRADE").get("value").toString();//优先级
        String recvBno = infoInputs.get("RECV_BNO").get("value").toString();//收款人行号
        String recvBname = infoInputs.get("RECV_BNAME").get("value").toString();//收款人行名
        String arriveWay = infoInputs.get("ARRIVE_WAY").get("value").toString();//到账方式
        bizExchangeInfo.setPayAcc(payAcc);
        bizExchangeInfo.setPayName(payName);
        bizExchangeInfo.setPayAddr(payAddr);
        bizExchangeInfo.setAmount(amount);
        bizExchangeInfo.setCerno(cerno);
        bizExchangeInfo.setCerdate(cerdate);
        bizExchangeInfo.setPaypwd(paypwd);
        bizExchangeInfo.setRecvAcc(recvAcc);
        bizExchangeInfo.setRecvName(recvName);
        bizExchangeInfo.setRecvAddr(recvAddr);
        bizExchangeInfo.setBusinessKind(businessKind);
        bizExchangeInfo.setRemarks(remarks);
        bizExchangeInfo.setGrade(grade);
        bizExchangeInfo.setRecvBno(recvBno);
        bizExchangeInfo.setRecvBname(recvBname);
        bizExchangeInfo.setAmount(amount);
        bizExchangeInfo.setArriveWay(arriveWay);
        String json = JSON.toJSONString(receiveParam);
        this.sysAbMessage.setMessageCheck(json);
        return persistence;
    }
    //授权岗提交方法
    @Override
    public PersistenceUtil executeAuth() throws Exception {
        TaskOtherCompleteParam receiveParam = (TaskOtherCompleteParam) this.receiveParam;
        TaskCompletePublicParam taskCompletePublicParam = receiveParam.getTaskCompletePublicParam();
        String completeMark = receiveParam.getTaskCompletePublicParam().getCompleteMark();
        String json = JSON.toJSONString(receiveParam);
        this.bizTranslist.setBackFlag(completeMark);//保存提交标志
        if (ConstantValue.CONDITION_PASS.equals(completeMark)) {
            BizAddImage bizAddImage = new BizAddImage();
            bizAddImage.setId(StringUtil.getId());
            bizAddImage.setJournalNo(taskCompletePublicParam.getJournalNo());
            bizAddImage.setStartTeller(taskCompletePublicParam.getCenterTellerNo());
            bizAddImage.setStartTellerName(taskCompletePublicParam.getCenterTellerName());
            bizAddImage.setStartDate(TimeUtil.getStandardTime());
            bizAddImage.setState("0");//默认未补扫
            bizAddImage.setNoPassReason(taskCompletePublicParam.getReason());
            persistence.addEntity(bizAddImage);
        }
        this.sysAbMessage.setMessageAuth(json);
        this.varMap.put("auth_flag", "0");

        return persistence;
    }

    @Override
    public PersistenceUtil executeNetwork() throws Exception {
        return null;
    }

    //回退方法
    @Override
    public PersistenceUtil executeBack() throws Exception {
        TaskBackParam receiveParam = (TaskBackParam) this.receiveParam;
        TaskBackPublicParam taskBackPublicParam = receiveParam.getTaskBackPublicParam();
        String backMark = taskBackPublicParam.getBackMark();
        String json = JSON.toJSONString(receiveParam);
        this.bizTranslist.setBackFlag(backMark);//保存提交标志
        this.sysAbMessage.setMessageAuth(json);
        this.varMap.put("auth_flag", backMark);
        return persistence;
    }

    @Override
    public Dto executeGetTaskList(NetHandle netHandle) {
        return new Dto();
    }

    @Override
    public PersistenceUtil executeTerminal() throws Exception {
        return persistence;
    }

    //整单获取
    @Override
    public Object executeTotalEntryTask() throws Exception {
        String message = sysAbMessage.getMessage();
        return JSON.parseObject(message, Map.class);
    }

    //修正岗获取
    public Object executeFixedTask() throws Exception {
        String message = sysAbMessage.getMessage();
        return JSON.parseObject(message, Map.class);
    }

    //验印岗获取
    public Object executeVerifyTask() throws Exception {
        String message = sysAbMessage.getMessage();
        return JSON.parseObject(message, Map.class);
    }

    //复核岗获取
    public Object executeReviewTask() throws Exception {
        String message = sysAbMessage.getMessage();
        return JSON.parseObject(message, Map.class);
    }

    //授权岗获取
    @Override
    public Object executeAuthTask() throws Exception {
        BizExchangeInfo bizExchangeInfo = bizExchangeInfoMapper.selectById(journalNo);
        Map<String, Map> otherFields = new HashMap<>();
        Map<String, Map> focusFields = new HashMap<>();
        Map<String, Map> authResult = new HashMap<>();
        QueryWrapper<BizDictSet> wrapper = new QueryWrapper<>();
        wrapper.eq("FIELD_TRANS_CODE", bizExchangeInfo.getTransCode());
        wrapper.eq("FIELD_TRANS_TYPE", bizExchangeInfo.getBsty());
        List<BizDictSet> dictSets = bizDictSetMapper.selectList(wrapper);//查询交易字段
        String messageTotal1 = sysAbMessage.getMessageTotal1();
        Map<String, Map> infoInputs = JSON.parseObject(messageTotal1, TaskOtherCompleteParam.class).getInfoInputs();
        Set<String> set = infoInputs.keySet();//中心录入字段
        String s = JSON.toJSONString(bizExchangeInfo);
        Map map = JSON.parseObject(s, Map.class);
        for (BizDictSet dictSet : dictSets) {
            String fieldEg = dictSet.getFieldEg();
            String field = StringUtil.slashToFirstLetterUpper(fieldEg);//转小写
            if ("1".equals(dictSet.getFieldFocus())) {
                HashMap<String, Object> focusField = new HashMap<>();
                if (set.contains(fieldEg)) {
                    focusField.put("sourceFlag", ConstantValue.SOURCE_FlAG_CENTER);//中心录入
                } else {
                    focusField.put("sourceFlag", ConstantValue.SOURCE_FlAG_BRANCH);//网点录入
                }
                focusField.put("CHE", dictSet.getFieldCn());//中文名
                focusField.put("value", map.get(field));//值
                focusFields.put(fieldEg, focusField);
            } else {
                HashMap<String, Object> otherField = new HashMap<>();
                if (set.contains(fieldEg)) {
                    otherField.put("sourceFlag", ConstantValue.SOURCE_FlAG_CENTER);//中心录入
                } else {
                    otherField.put("sourceFlag", ConstantValue.SOURCE_FlAG_BRANCH);//网点录入
                }
                otherField.put("CHE", dictSet.getFieldCn());
                otherField.put("value", map.get(field));
                otherFields.put(fieldEg, otherField);
            }
        }
        authResult.put("otherFields", otherFields);
        authResult.put("focusFields", focusFields);
        return authResult;
    }

    @Override
    public PersistenceUtil executeCharge() throws Exception {
        return null;
    }
}
